import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController, Item } from 'ionic-angular';
import { COMBO_DATA, COMBO_OUT } from '../../../common/combo'
import { ApiProvider } from '../../../providers/api/api';
import { NotificationProvider } from '../../../providers/notification/notification';
import { StorageProvider } from '../../../providers/storage/storage';
import { ToolProvider } from '../../../providers/tool/tool';
import { Observable } from 'rxjs';
import { HttpParams } from '@angular/common/http';
import { ZBar, ZBarOptions } from '@ionic-native/zbar';

/**
 * Generated class for the InstorePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-outstore',
  templateUrl: 'outstore.html'
})
export class OutstorePage {
  private houses: any;
  private houseId: string;
  private userId: string;
  private userName: string;
  private memo: string;
  private outTypes = COMBO_OUT.outType;
  private outType: string = '10';
  private details = []; //存放的是从库存选择的产品
  private fkeyid: string;
  private result: any;

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private api: ApiProvider,
    private notification: NotificationProvider,
    private modalCtrl: ModalController,
    private storage: StorageProvider,
    private tool: ToolProvider,
    private zbar: ZBar) {
  }

  ionViewDidLoad() {
    let userinfo = this.storage.getObject('userinfo');
    this.userId = userinfo.user_id;
    this.userName = userinfo.user_name;

    let res = this.api.getList('sp_house', { where_sql: 'sp_house.house_level=1', where_type: '', where_value: '' }).subscribe(res => {
      if (res['success']) {
        this.houses = res['data']['root'];
      } else {
        this.notification.showAlert(res['message']);
      }
      this.notification.hideLoading();
    })
  }

  /**
   * 打开选择modal(选择库存产品sp_store)
   */
  selStore() {
    let modal = this.modalCtrl.create('StoreSelPage', { house_id: this.houseId });
    let isExist = false;
    modal.onDidDismiss(data => {
      //数组的追加
      if (data) {
        this.details.forEach(item => {

          if (data.sp_store__store_id == item.sp_store__store_id) {
            this.notification.showToast("不能重复选择货品");
            isExist = true;

          }
        });
        if (!isExist) this.details.push(data);
      }
    })
    modal.present();
  }


  /**
   * 打开选择modal(选择业务员)
   */
  selUser() {
    let modal = this.modalCtrl.create('UserSelPage');
    modal.onDidDismiss(data => {
      if (data) {
        this.userId = data.sys_user__user_id;
        this.userName = data.sys_user__user_name;
      }
    })
    modal.present();
  }

  delete(item) {
    //splice() 方法用于插入、删除或替换数组的元素。注意：这种方法会改变原始数组！。
    this.details.splice(item);
  }

  getData(event, item) {
    item.sp_store__out_num = event.number;
  }

  /**
   * 
   * @param index
   */
  edit(index) {
    //this.selIndex = index;
    this.details[index].sp_store__house_id = this.houseId || '';
    let modal = this.modalCtrl.create('StoreEditPage', { item: this.details[index] });
    modal.onDidDismiss(data => {
      if (data) {
        this.details[index] = data;
      }
    })
    modal.present();
  }

  /**
   * 提交表单
   */
  commit() {
    //提示确认
    this.notification.showConfirm('提示', '是否提交该单据？', res => {
      if (res == 0) return;
      this.notification.showLoading("正在提交");
      //校验数据
      if (!this.validForm) return;
      //提交主表数据
      this.api.formSave(this.getFormParams())
        .subscribe(res => {
          if (!res['success']) {
            this.notification.hideLoading();
            this.notification.showToast(res['message']);
            return;
          }
          this.fkeyid = res['data'].keyid;
          this.api.gridSave(this.getGridParams()).subscribe(res => {
            if (!res['success']) {
              //res['message']
              this.notification.hideLoading();
              this.notification.showToast("请完善出库信息");
              return;
            }
            this.api.formAudit('sp_out', this.fkeyid).subscribe(res => {
              if (res['success']) {
                this.notification.hideLoading();
                this.notification.showToast("出库单已提交");
                this.navCtrl.pop();
              } else {
                this.notification.hideLoading();
                //res['message']
                this.notification.showToast(res['message']);
                return;
              }
            })
          })
        })
    });
  }

  /**
   * 校验表单数据
   */
  validForm(): boolean {
    if (!this.houseId) {
      this.notification.showToast("请选择仓库");
      return false;
    }
    if (!this.details || this.details.length == 0) {
      this.notification.showToast("请选择产品");
      return false;
    }
    this.details.forEach(detail => {
      let price = detail.sp_store__tax_price;
      if (!price) {
        this.notification.showToast("请填写价格");
        return false;
      }
      /** if(!stock){
        this.notification.showToast("请选择库位");
        return false;
      }*/
    });
    return true;
  }

  //获取表单参数
  getFormParams() {
    let userinfo = this.storage.getObject('userinfo'); //当前用户
    let houseName = '';
    let funid = '';
    //仓库名赋值
    this.houses.forEach(item => {
      if (item.sp_house__house_id == this.houseId) houseName = item.sp_house__house_name;
    });
    if (this.outType == '10') {
      funid = 'sp_out';
    } else {
      funid = 'sp_out_ext';
    }
    return {
      funid: funid,
      keyid: '',
      sp_out__auditing_out: '0',
      sp_out__house_user: this.userName,
      sp_out__house_name: houseName,
      sp_out__dept_id: userinfo.dept_id,
      sp_out__house_id: this.houseId,
      sp_out__out_code: '',
      sp_out__dept_name: userinfo.dept_name,
      sp_out__tax_money: '',
      sp_out__sec_dept: '',
      sp_out__apply_userid: 'administrator',
      sp_out__out_userid: '',
      sp_out__out_date: this.tool.getToday(),
      sp_out__user_name: userinfo.user_name,
      sp_out__out_type: this.outType,
      sp_out__out_id: '',
      sp_out__sec_deptid: '',
      sp_out__house_userid: this.userId,
      sp_out__user_id: userinfo.user_id,
      sp_out__out_memo: this.memo || ''
    }
  }

  /**
   * 获取明细数据
   */
  getGridParams(): string {
    let userinfo = this.storage.getObject('userinfo'); //当前用户
    let urlParams = 'funid=sp_out_det&&pfunid=sp_out&app_id=jxstar&fkValue=' + this.fkeyid + '&';
    if (!this.details || this.details.length == 0)
      return;
    this.details.forEach(item => {
      let indet = {
        keyid: '',
        pagetype: 'editgrid',
        sp_out_det__sp_code: item.sp_store__sp_code,
        sp_out_det__sp_name: item.sp_store__sp_name,
        sp_out_det__sp_type: item.sp_store__sp_type,
        sp_out_det__other_code: item.sp_store__other_code,
        sp_out_det__unit: item.sp_store__unit,

        sp_out_det__house_id: item.sp_store__house_id,

        sp_out_det__stock_id: item.sp_store__stock_id,
        sp_out_det__stock_name: item.sp_store__stock_name,
        sp_out_det__cur_num: item.sp_store__store_num,
        sp_out_det__out_num: item.sp_store__out_num,
        sp_out_det__tax_price: item.sp_store__out_price,
        sp_out_det__tax_money: item.sp_store__out_money,

        sp_out_det__in_date: item.sp_store__in_date,
        sp_out_det__store_type: item.sp_store__store_type,
        sp_out_det__store_code: item.sp_store__store_code,
        sp_out_det__memo: item.sp_store__out_memo || '',
        sp_out_det__out_id: this.fkeyid,
        sp_out_det__sp_id: item.sp_store__sp_id,
        sp_out_det__store_id: item.sp_store__store_id,
        sp_out_det__out_det_id: '', //出库明细主键
        sp_out_det__can_refund_num: '0',
      }
      if (urlParams) urlParams += '&';
      urlParams += this.tool.parseParams(indet);
    });
    return urlParams;
  }

  scan() {
    let options: ZBarOptions = {
      flash: 'off',
      text_title: '扫码',
      drawSight: false
    };

    this.zbar.scan(options)
      .then(result => {
        //alert("结果：" + result);  Scanned code

        let modal = this.modalCtrl.create('StoreSelPage', { house_id: this.houseId, sp_code: result });
        let isExist = false;
        modal.onDidDismiss(data => {
          //数组的追加
          if (data) {
            this.details.forEach(item => {

              if (data.sp_store__store_id == item.sp_store__store_id) {
                this.notification.showToast("不能重复选择货品");
                isExist = true;

              }
            });
            if (!isExist) this.details.push(data);
          }
        })
        modal.present();
      })
      .catch(error => {
        alert(error); // Error message
      });
  }
}
